package org.jeecg.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/biz/site")
@Api(tags="站点管理")
public class BizSiteController {

    @Autowired
    private IBizSiteService bizSiteService;

    @Autowired
    private IBizSiteUserService bizSiteRoleService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBizSiteUserService siteUserService;

    @ApiOperation(value = "查询站点", notes = "查询站点-列表分页查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<BizSiteEntity>> queryPageList(BizSiteEntity bizSiteEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {

        String username = JwtUtil.getUserNameByToken(req);
        Set<String> roles = sysUserService.getUserRolesSet(username);
        String roleStr = String.join(", ", roles);

        SysUser sysUser = sysUserService.getUserByName(username);

        Result<IPage<BizSiteEntity>> result = new Result<IPage<BizSiteEntity>>();
        QueryWrapper<BizSiteEntity> queryWrapper = new QueryWrapper<BizSiteEntity>();
        if(!roleStr.contains("admin") & !roleStr.contains("system")){

            if(StringUtils.isNotEmpty(bizSiteEntity.getSiteId())){
                queryWrapper.inSql("site_id","select site_id from biz_site_user where user_id='"+sysUser.getId()+"' and site_id='"+bizSiteEntity.getSiteId()+"'");
            }else{
                queryWrapper.inSql("site_id","select site_id from biz_site_user where user_id='"+sysUser.getId()+"'");
            }

        }else{
            if(StringUtils.isNotEmpty(bizSiteEntity.getSiteId())){
                queryWrapper.eq("site_id",bizSiteEntity.getSiteId());
            }
        }

        if(StringUtils.isNotEmpty(bizSiteEntity.getSiteDesc())){
            queryWrapper.like("site_desc",bizSiteEntity.getSiteDesc());
        }

        if(bizSiteEntity.getProvinceCode()!=null){
            queryWrapper.eq("province_code",bizSiteEntity.getProvinceCode());
        }

        if(bizSiteEntity.getCityCode()!=null){
            queryWrapper.eq("city_code",bizSiteEntity.getCityCode());
        }

        if(bizSiteEntity.getDistrictCode()!=null){
            queryWrapper.eq("district_code",bizSiteEntity.getDistrictCode());
        }

        if(bizSiteEntity.getStatus()!=null){
            queryWrapper.eq("status",bizSiteEntity.getStatus());
        }

        if (StringUtils.isNotEmpty(bizSiteEntity.getpSiteId())){
            queryWrapper.eq("p_site_id", bizSiteEntity.getpSiteId());
        }

        queryWrapper.orderByAsc("create_time");

        Page<BizSiteEntity> page = new Page<BizSiteEntity>(pageNo, pageSize);
        IPage<BizSiteEntity> pageList = bizSiteService.page(page, queryWrapper);

        List<BizSiteEntity> recordsWithUser =  new ArrayList<BizSiteEntity>();
        List<BizSiteEntity> records = pageList.getRecords();
        for(BizSiteEntity site : records){
            List<Map<?,?>> siteUserList = siteUserService.getSiteUserRealName(site.getSiteId());
            if(siteUserList !=null){
                site.setSiteUserList(siteUserList);
            }
            recordsWithUser.add(site);
        }
        pageList.setRecords(recordsWithUser);

        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "根据权限查询站点", notes = "查询站点-列表分页查询")
    @RequestMapping(value = "/listByUser", method = RequestMethod.GET)
    public Result<IPage<BizSiteEntity>> querySitePageListByUser(BizSiteEntity bizSiteEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, String userId,String type ,HttpServletRequest req) {
        Result<IPage<BizSiteEntity>> result = new Result<IPage<BizSiteEntity>>();

        if(StringUtils.isEmpty(userId)) {
            String username = JwtUtil.getUserNameByToken(req);
            SysUser sysUser = sysUserService.getUserByName(username);
            userId = sysUser.getId();
        }

        QueryWrapper<BizSiteEntity> queryWrapper = new QueryWrapper<BizSiteEntity>();
        if("include".equals(type)){
            queryWrapper.inSql("site_id","select site_id from biz_site_user a where a.status=1 and a.user_id='"+userId+"'");
        }else {
            queryWrapper.notInSql("site_id","select site_id from biz_site_user a where a.status=1 and a.user_id='"+userId+"'");
        }

        if(bizSiteEntity.getStatus()!=null){
            queryWrapper.eq("status",bizSiteEntity.getStatus());
        }


        Page<BizSiteEntity> page = new Page<BizSiteEntity>(pageNo, pageSize);
        IPage<BizSiteEntity> pageList = bizSiteService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "查询站点权限", notes = "查询站点权限-列表分页查询")
    @RequestMapping(value = "/listSiteUser", method = RequestMethod.GET)
    public Result<IPage<BizSiteUserEntity>> querySiteRolePageList(BizSiteUserEntity bizSiteRoleEntity, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                  @RequestParam(name="pageSize", defaultValue="100000") Integer pageSize, HttpServletRequest req) {
        Result<IPage<BizSiteUserEntity>> result = new Result<IPage<BizSiteUserEntity>>();
        QueryWrapper<BizSiteUserEntity> queryWrapper = QueryGenerator.initQueryWrapper(bizSiteRoleEntity, req.getParameterMap());
        queryWrapper.orderByAsc("create_time");
        Page<BizSiteUserEntity> page = new Page<BizSiteUserEntity>(pageNo, pageSize);
        IPage<BizSiteUserEntity> pageList = bizSiteRoleService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @ApiOperation(value = "新增站点", notes = "新增站点")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<BizSiteEntity> add(@RequestBody BizSiteEntity bizSiteEntity,HttpServletRequest request) {
        Result<BizSiteEntity> result = new Result<BizSiteEntity>();
        String username = JwtUtil.getUserNameByToken(request);
        try {
            QueryWrapper<BizSiteEntity> queryWrapper = new QueryWrapper();
            queryWrapper.eq("site_code",bizSiteEntity.getSiteCode());
            BizSiteEntity bizSiteOriginal = bizSiteService.getOne(queryWrapper);
            if(bizSiteOriginal!=null){
                result.error500("已存在site_code["+bizSiteEntity.getSiteCode()+"]");
                return result;
            }

            bizSiteEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
            bizSiteEntity.setCreatorId(username);
            bizSiteService.save(bizSiteEntity);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    @ApiOperation(value = "新增站点权限列表", notes = "新增站点权限列表")
    @RequestMapping(value = "/addSiteUserList", method = RequestMethod.POST)
    public Result<BizSiteUserEntity> addSiteUserList(@RequestBody List<BizSiteUserEntity> bizSiteRoleEntityList, HttpServletRequest request) {
        Result<BizSiteUserEntity> result = new Result<BizSiteUserEntity>();
        String username = JwtUtil.getUserNameByToken(request);
        try {

            List<BizSiteUserEntity> addSiteUserList = new ArrayList<BizSiteUserEntity>();
            for(BizSiteUserEntity bizSiteUserEntity:bizSiteRoleEntityList){
                QueryWrapper<BizSiteUserEntity> queryWrapper = new QueryWrapper();
                queryWrapper.eq("site_id",bizSiteUserEntity.getSiteId());
                queryWrapper.eq("user_id",bizSiteUserEntity.getUserId());
                if(bizSiteRoleService.count(queryWrapper)==0){
                    bizSiteUserEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    bizSiteUserEntity.setCreateBy(username);
                    addSiteUserList.add(bizSiteUserEntity);
                }

            }

            bizSiteRoleService.saveBatch(addSiteUserList);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }

    @ApiOperation(value = "更新站点权限列表", notes = "更新站点权限列表")
    @RequestMapping(value = "/modSiteUserList", method = RequestMethod.POST)
    public Result<BizSiteUserEntity> modSiteUserList(@RequestBody List<BizSiteUserEntity> bizSiteRoleEntityList, HttpServletRequest request) {
        Result<BizSiteUserEntity> result = new Result<BizSiteUserEntity>();
        String username = JwtUtil.getUserNameByToken(request);
        try {

            for(BizSiteUserEntity bizSiteUserEntity:bizSiteRoleEntityList){
                QueryWrapper<BizSiteUserEntity> queryWrapper = new QueryWrapper();
                queryWrapper.eq("site_id",bizSiteUserEntity.getSiteId());
                queryWrapper.eq("user_id",bizSiteUserEntity.getUserId());
                BizSiteUserEntity o =bizSiteRoleService.getOne(queryWrapper);

                //原来有记录的就变更
                if(o !=null && StringUtils.isNotEmpty(o.getId())){
                    o.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    o.setUpdateBy(username);
                    o.setSiteId(bizSiteUserEntity.getSiteId());
                    o.setUserId(bizSiteUserEntity.getUserId());
                    o.setStatus(bizSiteUserEntity.getStatus());
                    bizSiteRoleService.update(o,queryWrapper);
                }else{
                    bizSiteUserEntity.setCreateBy(username);
                    bizSiteUserEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    bizSiteRoleService.save(bizSiteUserEntity);
                }

            }
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result.error500("操作失败");
        }
        return result;
    }


    @ApiOperation(value = "编辑站点", notes = "编辑站点")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result<BizSiteEntity> edit(@RequestBody BizSiteEntity bizSiteEntity,HttpServletRequest request) {
        Result<BizSiteEntity> result = new Result<BizSiteEntity>();
        String username = JwtUtil.getUserNameByToken(request);
        BizSiteEntity bizSiteOriginal = bizSiteService.getById((Serializable) bizSiteEntity.getSiteId());
        if(bizSiteOriginal==null) {
            result.error500("未找到对应实体");
        }else {
            bizSiteEntity.setModifyTime(DateUtils.getTimestamp());
            bizSiteEntity.setModifierId(username);
            boolean ok = bizSiteService.updateById(bizSiteEntity);
            if(ok) {
                result.success("编辑成功!");
            }
        }
        return result;
    }

    @ApiOperation(value = "查询不同状态的站点数量", notes = "查询设备状态数-在线状态：1-正常；2-异常")
    @RequestMapping(value = "/listStatusCount", method = RequestMethod.GET)
    public Result<List<Map<?,?>>> listStatusCount(HttpServletRequest req) {
        Result<List<Map<?,?>>> result = new Result<List<Map<?,?>>>();
        result.setResult(bizSiteService.getStatusCount());
        result.success("查询成功!");
        return result;
    }

}
